<template>
  <div class="page-container">
    <!-- 左上角返回主页按钮 -->
    <div class="back-home" @click="goToHome">
      <span>< 返回主页</span>
    </div>

    <div class="user-profile">
      <!-- 头部信息区域 -->
      <div class="profile-header">
        <img 
          class="avatar" 
          :src="user.avatar || defaultAvatar" 
          alt="用户头像" 
          style="background: #f0f0f0;"
        />
        <div class="info" :style="{ opacity: userLoaded ? 1 : 0, transition: 'opacity 0.3s ease' }">
          <h2 class="username">{{ user.name }}</h2>
          <p class="desc">{{ user.description }}</p>
          <span class="location">{{ user.address }}</span>
        </div>
        <!-- 编辑资料按钮（改为黑色） -->
        <el-button class="edit-btn" @click="handleEdit">编辑资料</el-button>
        <el-button class="edit-btn" @click="upload">发布笔记</el-button>
        <el-button class="edit-btn" @click="chat">个人消息</el-button>
      </div>
      <!-- 统计数据区域 -->
      <div class="stats">
        <div class="stat-item">
          <span class="stat-num">{{ user.publishCount }}</span>
          <span class="stat-text">发布</span>
        </div>
        <div class="stat-item">
          <span class="stat-num">{{ user.collectCount }}</span>
          <span class="stat-text">收藏</span>
        </div>
        <div class="stat-item">
          <span class="stat-num">{{ user.commentCount }}</span>
          <span class="stat-text">评论</span>
        </div>
      </div>
      <!-- 标签切换区域 -->
      <div class="tabs">
        <span 
          class="tab-item" 
          :class="{ active: activeTab === 'notes' }" 
          @click="clickNode"
        >笔记</span>
        <span 
          class="tab-item" 
          :class="{ active: activeTab === 'collects' }" 
          @click="clickCollect"
        >收藏</span>
      </div>
    </div>
    <div class="home-container">
      <!-- 瀑布流 -->
      <waterfall :col="calcColumns()" :width="calcItemWidth()" :gutterWidth="15" :data="itemsWithUser"
        @loadmore="loadMore" :loadDistance="20">
        <div class="cell-item" v-for="item in items" :key="item.id" @click="showBlog(item, $event)">
          <img 
            :src="item.img" 
            alt="博客图片" 
            @error="handleImageError" 
            style="height: 200px; background: #f7f7f7;"
            loading="lazy"
          />
          <div class="item-body">
            <div class="item-desc">{{ item.blogName }}</div>
            <div class="item-footer">
              <div class="footer-left">
                <img class="item-img" :src="item.user?.avatar || defaultAvatar" alt="用户头像" @error="handleAvatarError" />
                <div class="name">{{ item.user?.name || "未知用户" }}</div>
              </div>
              <div class="footer-right">
                <el-icon :size="16" @click.stop="handleCollect(item)">
                  <component :is="item.isCollected ? StarFilled : Star" />
                </el-icon>
                <span>{{ item.count }}</span>
              </div>
            </div>
          </div>
        </div>
      </waterfall>

      <!-- blog详情框（带关闭按钮×） -->
      <div class="custom-dialog-container" v-show="visible">
        <!-- 右上角关闭按钮× -->
        <button class="close-btn" @click="closeModal">×</button>
        
        <div class="custom-dialog-content">
          <div class="img-video-container">
            <video controls autoplay muted :src="blogItem.video" class="video-player" v-if="blogItem.category === '视频'"></video>
            <el-image :src="blogItem.img || defaultImage" class="img" :preview-src-list="[blogItem.img]" v-else @error="handleImageError"></el-image>
          </div>
          <div class="blog-container">
            <div class="user-info">
              <img :src="blogItem.avatar || defaultAvatar" alt="User Avatar" class="user-avatar" @error="handleAvatarError" />
              <span class="user-name">{{ blogItem.name }}</span>
            </div>
            <h2 class="blog-title">{{ blogItem.blogName }}</h2>
            <p class="blog-description" v-html="blogItem.content"></p>
            <span class="blog-time">{{ blogItem.time }}</span>
            <el-divider></el-divider>

            <!-- 评论区 -->
            <div style="margin: 28px 0">
              <div style="padding: 10px 0; font-size: 16px; margin-top: 5px; margin-bottom: 5px; color: #8c939d">
                共 {{ blogItem.commentCount }} 条评论
              </div>
              
              <!-- 评论列表（带滚动条） -->
              <div class="comment-warp">
                <div v-for="item in blogItem.comments" :key="item.id" class="comment-item">
                  <div class="comment-avatar">
                    <el-image :src="item.user?.avatar || defaultAvatar" @error="handleAvatarError"></el-image>
                  </div>
                  <div class="comment-main">
                    <div class="comment-info">
                      <span class="comment-name">{{ item.user?.name || "未知用户" }}</span>
                      <span class="comment-text">{{ item.content }}</span>
                    </div>
                    <div class="comment-ops">
                      <span class="comment-time">{{ item.time }}</span>
                      <el-button type="text" size="small" @click="handleReply(item.id)">回复</el-button>
                      <el-button type="text" size="small" @click="del(item.id)" v-if="conllection.userId === item.userId">删除</el-button>
                    </div>

                    <!-- 回复输入框 -->
                    <div class="reply-input" v-if="commentForm.pid === item.id && replyVisible">
                      <el-input v-model="commentForm.contentReply" placeholder="输入回复内容..." autocomplete="off"></el-input>
                      <div class="reply-btns">
                        <el-button size="mini" type="primary" @click="save">发送</el-button>
                        <el-button size="mini" @click="cancelReply">取消</el-button>
                      </div>
                    </div>

                    <!-- 子评论 -->
                    <div class="children-comments" v-if="item.children && item.children.length">
                      <div v-for="subItem in item.children" :key="subItem.id" class="comment-item child-comment">
                        <div class="comment-avatar">
                          <el-image :src="subItem.user?.avatar || defaultAvatar" @error="handleAvatarError"></el-image>
                        </div>
                        <div class="comment-main">
                          <div class="comment-info">
                            <span class="comment-name">{{ subItem.user?.name || "未知用户" }}</span>
                            <span v-if="subItem.pid" class="reply-at">回复 @{{ item.user?.name }}</span>
                            <span class="comment-text">{{ subItem.content }}</span>
                          </div>
                          <div class="comment-ops">
                            <span class="comment-time">{{ subItem.time }}</span>
                            <el-button type="text" size="small" @click="handleReply(subItem.id)">回复</el-button>
                            <el-button type="text" size="small" @click="del(subItem.id)" v-if="conllection.userId === subItem.userId">删除</el-button>
                          </div>

                          <!-- 子评论回复框 -->
                          <div class="reply-input" v-if="commentForm.pid === subItem.id && replyVisible">
                            <el-input v-model="commentForm.contentReply" placeholder="输入回复内容..." autocomplete="off"></el-input>
                            <div class="reply-btns">
                              <el-button size="mini" type="primary" @click="save">发送</el-button>
                              <el-button size="mini" @click="cancelReply">取消</el-button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 新增：固定在底部的一级评论框 -->
              <div class="top-comment-container">
                <div class="top-comment-input">
                  <el-input 
                    v-model="comment.content" 
                    placeholder="分享你的想法..." 
                    autocomplete="off" 
                    :rows="3" 
                    type="textarea"
                    class="custom-textarea"
                  ></el-input>
                  <div class="top-comment-btn">
                    <el-button type="primary" @click="sendComment" >
                      发布评论
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed, onBeforeUnmount } from "vue";
import {
  findBlogByType,
  Collect,
  getIsCollected,
  getCommentTree,
  addFirstComment,
  addCommentReply,
  deleteComment,
  findUserInfoByUserId,
  getConllectionCount,
  getPublishCount,
  getCommentCount,
  findUserBlog,
  findUserCollectBlog,
} from "@/api/life";
import { ElIcon, ElButton } from "element-plus";
import { Star, StarFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import router from '@/router';
// import Waterfall from 'vue-waterfall2'; 


defineExpose({ Star, StarFilled });

// 创建响应式User对象
const user = reactive({
  avatar: '',
  name: '',
  description: '',
  address: '',
  publishCount: 0,
  collectCount: 0,
  commentCount: 0
})

const activeTab = ref('notes');
const userLoaded = ref(false); // 标记用户数据是否加载完成

//编辑个人信息
const handleEdit = async () => {
  await new Promise(resolve => setTimeout(resolve, 50));
  await router.push("/UpdateLifePerson")
};

// 发布笔记
const upload = async () => {
  await new Promise(resolve => setTimeout(resolve, 50));
  await router.push("/UploadNotes")
};

// 发布笔记
const chat = async () => {
  await new Promise(resolve => setTimeout(resolve, 50));
  await router.push("/lifeChat")
};

const goToHome = async() => {
  await new Promise(resolve => setTimeout(resolve, 50));
  router.push('/LifeCircle');
};

// 定义响应式数据
const typeId = ref(0);
const conllection = reactive({
  userId: 3,
  itemId: "",
});
const items = ref([]);
const page = reactive({
  pageNum: 1,
  pageSize: 100,
  isLoading:false,
});

const visible = ref(false);

const blogItem = ref({
  id: "",
  img: "",
  avatar: "",
  name: "",
  blogName: "",
  content: "",
  time: "",
  commentCount: 0,
  category: "",
  video: "",
  comments: []
});

const comment = ref({
  content: '',
  userId: '',
  time: '',
  pid: '',
  originId: '',
  itemId: '',
});

const commentForm = reactive({
  pid: 0,
  contentReply: ''
});
const replyVisible = ref(false);

const defaultAvatar = "https://picsum.photos/200/200";
const defaultImage = "https://picsum.photos/800/600";

// 防抖函数
const debounce = (fn, delay = 100) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
};


//点击笔记进入查找自己发布的博客
const clickNode = ()=>{
  activeTab.value = 'notes'
  findUserAllBlog(conllection.userId)
}

//点击收藏进入自己的收藏页面
const clickCollect =()=>{
  activeTab.value = 'collects'
  findUserAllConllectBlog(conllection.userId)
}

//查找发布的博客
const findUserAllBlog = async (userId) => {
  page.pageNum = 1;
  try {
    const res = await findUserBlog(page.pageNum, page.pageSize, userId);
    items.value = res.data.list || [];
    await getConlectBoolean(items.value);
  } catch (error) {
    console.error("获取博客失败:", error);
    items.value = [];
  }
};

//查找收藏的博客
const findUserAllConllectBlog = async (userId) => {
  page.pageNum = 1;
  try {
    const res = await findUserCollectBlog(page.pageNum, page.pageSize, userId);
    items.value = res.data.list || [];
    await getConlectBoolean(items.value);
  } catch (error) {
    console.error("获取博客失败:", error);
    items.value = [];
  }
};

// 计算列数（带防抖）
const calcColumns = debounce(() => {
  const width = window.innerWidth;
  if (width < 600) return 2;
  if (width < 900) return 3;
  if (width < 1200) return 4;
  return 5;
});

// 计算每项宽度（带防抖）
const calcItemWidth = debounce(() => {
  const baseWidth = 280;
  const columns = calcColumns();
  const maxWidth = Math.floor((window.innerWidth - 60) / columns);
  return Math.min(baseWidth, maxWidth);
});

// 加载更多
// const loadMore = async () => {
//   page.pageNum++;

//   try {
//     const res = await findBlogByType(page.pageNum, page.pageSize, typeId.value);
//     if (res.data.list && res.data.list.length > 0) {
//       items.value = [...items.value, ...res.data.list];
//     } else {
//       page.pageNum--;
//     }
//   } catch (error) {
//     page.pageNum--;
//     console.error("加载更多失败:", error);
//   }
// };
const loadMore = async () => {
  // 1. 防重复请求：正在加载时直接返回
  if (page.isLoading) return; 
  page.isLoading = true;  

  page.pageNum++;

  try {
    const res = await findBlogByType(page.pageNum, page.pageSize, typeId.value);
    
    // 2. 数据校验：确保返回结构符合预期
    if (!res?.data?.list || !Array.isArray(res.data.list)) {
      throw new Error("接口返回数据格式异常");
    }

    if (res.data.list.length > 0) {
      items.value = [...items.value, ...res.data.list];
    } else {
      page.pageNum--; // 无更多数据回退
    }
  } catch (error) {
    page.pageNum--; // 出错回退
    console.error("加载更多失败:", error);
    // 3. 可选：触发全局错误提示
    ElMessage.error("加载更多失败，请稍后重试"); 
  } finally {
    page.isLoading = false; // 4. 无论成功失败，释放加载锁
  }
};

// 收藏
const handleCollect = async (item) => {
  conllection.itemId = item.id;
  try {
    const res = await Collect(conllection);
    ElMessage[res.code === 200 ? "success" : "error"](res.message);
    getConlectBoolean(item);
  } catch (error) {
    ElMessage.error("请求失败，请重试");
  }
};

// 打开模态框
const showBlog = (item, $event) => {
  blogItem.value.img = item.img;
  blogItem.value.avatar = item.user?.avatar;
  blogItem.value.name = item.user?.name;
  blogItem.value.content = item.content;
  blogItem.value.blogName = item.blogName;
  blogItem.value.time = item.time;
  blogItem.value.commentCount = item.commentCount;
  blogItem.value.id = item.id;
  blogItem.value.category = item.category;
  blogItem.value.video = item.video;
  getComments();
  visible.value = true;
};

// 关闭模态框
const closeModal = () => {
  visible.value = false;
  comment.value.content = "";
  commentForm.pid = 0;
  commentForm.contentReply = "";
  replyVisible.value = false;
};

// 发送评论
const sendComment = async () => {
  if (!comment.value.content.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }

  try {
    comment.value.userId = conllection.userId;
    comment.value.itemId = blogItem.value.id;
    const res = await addFirstComment(comment.value);
    if (res.code === 200) {
      ElMessage.success("评论发布成功");
      await getComments();
      // changeType(typeId.value);
      blogItem.value.commentCount++;
      comment.value.content = "";
    } else {
      ElMessage.error("发布失败：" + (res.msg || res.message));
    }
  } catch (error) {
    ElMessage.error("网络异常，请重试");
  }
};

// 图片加载错误处理
const handleImageError = (e) => {
  e.target.src = defaultImage;
};

const handleAvatarError = (e) => {
  e.target.src = defaultAvatar;
};

// 获取收藏状态
const getConlectBoolean = async (items) => {
  const itemList = Array.isArray(items) ? items : [items];
  for (const item of itemList) {
    conllection.itemId = item.id;
    try {
      const res = await getIsCollected(conllection.userId, conllection.itemId);
      item.isCollected = JSON.parse(res.data.isCollected);
      item.count = res.data.count;
    } catch (error) {
      console.error("状态值请求失败，请重试");
    }
  }
};

// 获取评论
const getComments = async () => {
  try {
    const res = await getCommentTree(blogItem.value.id);
    blogItem.value.comments = res.data || [];
  } catch (error) {
    console.error("评论数据请求失败，请重试");
    blogItem.value.comments = [];
  }
};

// 获取用户ID
const getUserId = async() => {
  const userStr = localStorage.getItem("user");
  const user = userStr ? JSON.parse(userStr) : null;
  if (user && user.userId) {
    conllection.userId = user.userId;
    getUserNameAndAvatar(conllection.userId);
    getUserPublishCount(conllection.userId);
    getUserConllectionCount(conllection.userId);
    getUserCommentCount(conllection.userId);
    await findUserAllBlog(conllection.userId)
  } else {
    console.log("localStorage 中未找到有效的 user 数据,使用默认userId=3");
  }
};

// 获取用户信息
const getUserNameAndAvatar = async (userId) => {
  try {
    const res = await findUserInfoByUserId(userId);
    user.avatar = res.data.avatar;
    user.name = res.data.name;
    user.address = res.data.address;
    user.description = res.data.description;
  } catch (error) {
    console.error("NameAndAvatar数据请求失败,请重试");
  } finally {
    userLoaded.value = true; // 无论成功失败都标记为已加载
  }
};

// 获取发布数量
const getUserPublishCount = async (userId) => {
  try {
    const res = await getPublishCount(userId);
    user.publishCount = res.data;
  } catch (error) {
    console.error("PublishCount数据求失败,请重试");
  }
};

// 获取收藏数量
const getUserConllectionCount = async (userId) => {
  try {
    const res = await getConllectionCount(userId);
    user.collectCount = res.data;
  } catch (error) {
    console.error("ConllectionCount数据求失败,请重试");
  }
};

// 获取评论数量
const getUserCommentCount = async (userId) => {
  try {
    const res = await getCommentCount(userId);
    user.commentCount = res.data;
  } catch (error) {
    console.error("CommentCount数据求失败,请重试");
  }
};

// 提交回复
const save = async () => {
  if (!commentForm.contentReply.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }

  try {
    comment.value.content = commentForm.contentReply.trim();
    comment.value.userId = conllection.userId;
    comment.value.itemId = blogItem.value.id;
    comment.value.pid = commentForm.pid;
    const res = await addCommentReply(comment.value);
    if (res.code === 200) {
      ElMessage.success('回复成功');
      await getComments();
      // changeType(typeId.value);
      blogItem.value.commentCount++;
      commentForm.contentReply = '';
      cancelReply();
    } else {
      ElMessage.error('回复失败：' + (res.msg || res.message));
    }
  } catch (error) {
    ElMessage.error('网络异常，回复失败');
  }
};

// 取消回复
const cancelReply = () => {
  commentForm.pid = 0;
  commentForm.contentReply = '';
  replyVisible.value = false;
};

// 处理回复
const handleReply = (pid) => {
  commentForm.pid = pid;
  replyVisible.value = true;
  setTimeout(() => {
    const input = document.querySelector('.reply-input .el-input__inner');
    input?.focus();
  }, 100);
};

// 删除评论
const del = async (commentId) => {
  try {
    const res = await deleteComment(commentId);
    if (res.code === 200) {
      ElMessage.success('删除成功');
      await getComments();
      // changeType(typeId.value);
      blogItem.value.commentCount--;
    } else {
      ElMessage.error('删除失败：' + (res.msg || res.message));
    }
  } catch (error) {
    ElMessage.error('网络异常，删除失败');
  }
};

// 初始化
onMounted(async () => {
  getUserId();

  // 窗口resize防抖处理
  const handleResize = debounce(() => {
    // 触发瀑布流重计算（如需要）
  }, 100);
  window.addEventListener('resize', handleResize);

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
  });
});
</script>

<style lang="scss" scoped>
/* 页面容器 */
.page-container {
  position: relative;
  padding: 20px;
}

/* 返回主页按钮样式 */
.back-home {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #666;
  cursor: pointer;
  padding: 6px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.2s;
}

.back-home:hover {
  background-color: #e5e5e5;
  color: #333;
}

/* 编辑资料按钮改为黑色 */
.edit-btn {
  background-color: #333 !important;
  border-color: #333 !important;
  color: #fff !important;
}

.edit-btn:hover {
  background-color: #1a1a1a !important;
  border-color: #1a1a1a !important;
}

//头部区域样式
.user-profile {
  width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  // 去掉阴影
  border-radius: 8px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  min-height: 100px; // 固定最小高度
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 16px;
  object-fit: cover; // 确保图片正确显示
}

.info {
  flex: 1;
}

// 文本元素添加最小高度防止抖动
.username {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
  min-height: 24px;
}

.desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
  min-height: 18px;
}

.location {
  font-size: 12px;
  color: #999;
  min-height: 16px;
}

.edit-btn {
  padding: 6px 16px;
  font-size: 14px;
}

.stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-num {
  font-size: 18px;
  font-weight: bold;
  display: block;
  margin-bottom: 4px;
}

.stat-text {
  font-size: 14px;
  color: #999;
}

.tabs {
  display: flex;
  justify-content: center;
  gap: 40px;
}

.tab-item {
  font-size: 16px;
  color: #333;
  cursor: pointer;
  padding-bottom: 4px;
  border-bottom: 2px solid transparent;
}

.tab-item.active {
  color: #ff6600;
  border-bottom-color: #ff6600;
}

// 基础样式
.home-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 0 15px;
}

.cell-item {
  max-width: 100%;
  margin-bottom: 15px;
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  img {
    width: 100%;
    object-fit: cover;
    border-radius: 6px 6px 0 0;
  }

  .item-body {
    padding: 10px;

    .item-desc {
      font-size: 16px;
      color: #333;
      margin-bottom: 8px;
    }

    .item-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .footer-left {
        display: flex;
        align-items: center;

        .item-img {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          margin-right: 8px;
        }

        .name {
          font-size: 14px;
          color: #666;
        }
      }

      .footer-right {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #999;

        i {
          margin-right: 4px;
          cursor: pointer;
        }
      }
    }
  }
}

// 详情框样式（带关闭按钮×）
.custom-dialog-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;

  // 关闭按钮×（右上角）
  .close-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 36px;
    height: 36px;
    background: #fff;
    border: none;
    border-radius: 50%;
    font-size: 20px;
    color: #666;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.2s;

    &:hover {
      background: #f5f5f5;
      color: #333;
    }
  }
}

.custom-dialog-content {
  width: 90%;
  max-width: 1000px;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
  display: flex;
  max-height: 90vh;

  @media (max-width: 768px) {
    flex-direction: column;
    max-height: 95vh;
  }
}

.img-video-container {
  width: 40%;
  background: #f7f7f7;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;

  video, .img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    max-height: 90vh;
  }

  @media (max-width: 768px) {
    width: 100%;
    height: 300px;
  }
}

.blog-container {
  width: 60%;
  padding: 24px;
  overflow-y: auto;

  .user-info {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .user-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 12px;
    }

    .user-name {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .blog-title {
    font-size: 22px;
    font-weight: 700;
    color: #333;
    margin: 0 0 16px;
  }

  .blog-description {
    font-size: 15px;
    color: #666;
    line-height: 1.7;
    margin-bottom: 20px;
    word-break: break-word;
  }

  .blog-time {
    font-size: 13px;
    color: #999;
    margin-bottom: 20px;
    display: inline-block;
  }

  @media (max-width: 768px) {
    width: 100%;
    padding: 16px;
  }
}

// 评论区样式
.comment-warp {
  margin-top: 20px;
  max-height: 400px;
  overflow-y: auto;
  padding-right: 8px;
  margin-bottom: 120px; // 预留一级评论框高度
}

// 优化滚动条样式
.comment-warp::-webkit-scrollbar {
  width: 6px;
}
.comment-warp::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}
.comment-warp::-webkit-scrollbar-track {
  background-color: #f9f9f9;
}

.comment-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  // 子评论样式（缩进+左侧线）
  &.child-comment {
    margin-left: 24px;
    padding-left: 16px;
    border-left: 1px dashed #e5e5e5;
  }
}

.comment-avatar {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  margin-right: 12px;

  .el-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
  }
}

.comment-main {
  flex: 1;
  min-width: 0;
}

.comment-info {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 8px;

  .comment-name {
    font-size: 14px;
    font-weight: 600;
    color: #333;
  }

  .reply-at {
    font-size: 14px;
    color: #999;
  }

  .comment-text {
    font-size: 14px;
    color: #555;
    line-height: 1.5;
    word-break: break-word;
  }
}

.comment-ops {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 12px;
  color: #999;

  .comment-time {
    color: #999;
  }

  .el-button {
    padding: 0;
    color: #666;
    font-size: 12px;

    &:hover {
      color: #ff6a00;
    }
  }
}

// 回复输入框
.reply-input {
  margin-top: 12px;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 8px;

  .el-input {
    width: 100%;
    margin-bottom: 10px;

    &::v-deep .el-input__inner {
      border-radius: 6px;
      border-color: #e5e5e5;
    }
  }

  .reply-btns {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
}

// 子评论容器
.children-comments {
  margin-top: 12px;
}

// 一级评论框容器
.top-comment-container {
  display: flex;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-top: 16px;
  align-items: flex-start;
}

// 输入框区域
.top-comment-input {
  flex: 1;
  width: 0;

  .custom-textarea {
    &::v-deep .el-textarea__inner {
      border-radius: 12px;
      border-color: #e0e0e0;
      padding: 12px 16px;
      resize: none;
      font-size: 14px;
      line-height: 1.6;
      transition: border-color 0.2s;

      &:focus {
        border-color: #ff6a00;
        box-shadow: 0 0 0 2px rgba(255, 106, 0, 0.1);
      }
    }
  }
}

// 发布按钮
.top-comment-btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;

  .el-button {
    padding: 8px 24px;
    border-radius: 20px;
    background-color: #ff6a00;
    border-color: #ff6a00;

    &:hover {
      background-color: #e05a00;
      border-color: #e05a00;
    }

    &:disabled {
      background-color: #f5f5f5;
      border-color: #e0e0e0;
      color: #999;
      cursor: not-allowed;
    }
  }
}
</style>